import json
from flask import Blueprint, request, jsonify
from controllers.common import *
from controllers.db import *

auction_event_project_api = Blueprint('auction_event_project_api', __name__)
auction_event_project_down_api = Blueprint('auction_event_project_down', __name__)


@auction_event_project_api.route('/auction_event_project', methods=['POST'])
def auction_event_project():
    params = json.loads(request.data)
    action = params['action']
    project = params['project']
    result_data = {'status': 200, 'data': {'msg': '', 'ret': 0, 'type': 'success', 'env': EVN, 'item': ''}}
    if action == 'index':
        query = AuctionEventProject.query.order_by('project').all()
        result = []

        for que in query:
            basic = json.loads(que.basic)
            castle_lv = basic['castle_lv'] if 'castle_lv' in basic else '未填写'
            ticket = basic['ticket'] if 'ticket' in basic else '未填写'
            tmp = {
                "project": int(que.project),
                'castle_lv': castle_lv,
                'ticket': ticket,
                'remark': str(que.remark)
            }
            result.append(tmp)
        result_data['data']['item'] = result

    elif action == 'clone':
        project_data = AuctionEventProject.query.filter_by(project=project).first()
        new_project_data = AuctionEventProject(
            basic=project_data.basic,
            goods=project_data.goods,
            remark=project_data.remark
        )
        db.session.add(new_project_data)
        db.session.commit()
        new_project_id = new_project_data.project
        if new_project_id is None:
            result_data['status'] = 500
            result_data['data']['msg'] = "克隆失败"
        else:
            result_data['data']['msg'] = "克隆成功"

    elif action == 'remark':
        remark = str(params['remark'])
        AuctionEventProject.query.filter_by(project=project).update({'remark': remark})
        db.session.commit()
        result_data['data']['msg'] = "备注修改成功"

    elif action == 'delete':
        project_data = AuctionEventProject.query.filter_by(project=project).first()
        db.session.delete(project_data)
        db.session.commit()
        que_project_data = AuctionEventProject.query.filter_by(project=project).first()
        if que_project_data is not None:
            result_data['status'] = 500
            result_data['data']['msg'] = "删除失败"
        else:
            result_data['data']['msg'] = "删除成功"

    elif action == 'detail':
        query = AuctionEventProject.query.filter_by(project=project).first()
        basic = json.loads(query.basic)
        goods = json.loads(query.goods)
        project = query.project

        tmp = {
            "project": project,
            'basic': basic,
            'goods': goods
        }
        result_data['data']['item'] = tmp

    elif action == 'doc_id_list':
        doc_file_data = GetDocByFilename('auction_event')
        result = []
        for k, v in doc_file_data.items():
            result.append({
                'value': int(k),
                'label': '{0}-{1}'.format(k, v['title'])
            })
        return json.dumps(result)

    elif action == 'update_part':
        data = params['data']
        part = params['part']

        if part == 'basic':
            AuctionEventProject.query.filter_by(project=project).update({
                'basic': json.dumps(data)
            })

        elif part == 'goods':
            AuctionEventProject.query.filter_by(project=project).update({
                'goods': json.dumps(data)
            })

        db.session.commit()
        result_data['data']['msg'] = "更新成功"

    return jsonify(result_data)


@auction_event_project_down_api.route('/auction_event_project_down/<int:is_push>', methods=['GET', 'POST'])
def auction_event_project_down(is_push):
    result = {}
    query = AuctionEventProject.query.order_by('project').all()

    auction_data = read_s3_file('auction')

    for que in query:
        pid = que.project
        basic = json.loads(que.basic)
        goods = json.loads(que.goods)

        if 'calendar_doc_id' in basic:
            _calendar_doc_id = basic['calendar_doc_id']
        else:
            _calendar_doc_id = 1
        if 'calendar_reward' in basic:
            calendar_reward = RewardToTMysqlNew(basic['calendar_reward'])
        else:
            calendar_reward = []

        new_goods = []
        for node in goods:
            cur_cycle = []
            reward_list = node['reward']
            for reward_node in reward_list:
                reward_tmp = [
                    {'a': [reward_node['type'],
                           reward_node['id'],
                           reward_node['num']]
                    },
                    reward_node['starting_price'],
                    reward_node['price_add']
                ]
                cur_cycle.append(reward_tmp)
            new_goods.append(cur_cycle)

        tmp = {
            'calendar_conf': {
                'event_type': 33,
                'event_ui': 1,
                'order': 1,
                'jump': 1,
                'localization': {
                    'title': _calendar_doc_id,
                    'info': _calendar_doc_id
                },
                'reward': calendar_reward,
                'show_type': 0
            },
            'castle_lv': basic['castle_lv'],
            'ticket': basic['ticket'],
            'topn': basic['topn'],
            'goods': new_goods
        }
        result[str(pid)] = tmp

    auction_data['proj'] = result

    response = DownLoad('auction', auction_data, is_push)

    return response
